package cn.doctor.assistant.pad.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import cn.doctor.assistant.pad.MyApplication;

public class UnreadCountDBManager extends DBBase{
	
	public static final String table = "unreadcount";

	private static UnreadCountDBManager instance;
	public synchronized static UnreadCountDBManager getInstance(){
		if(instance == null){
			instance = new UnreadCountDBManager();
		}
		return instance;
	}

	public synchronized int getUnreadCount(String username) {
		SQLiteDatabase sqlDB = DBHelper.getSQLiteDatabase();
		if(!tableIsExist(sqlDB, table)) return 0;
		Cursor cursor = sqlDB.rawQuery("select count from unreadcount where username = ?", new String[] { username });

		int count = 0;
		if (cursor.moveToFirst()) {
			count = cursor.getInt(0);
		}
		cursor.close();
		return count;
	}

	public synchronized int getAllUnreadCount() {
		SQLiteDatabase sqlDB = DBHelper.getSQLiteDatabase();
		if(!tableIsExist(sqlDB, table)) return 0;
		String username = MyApplication.getInstance().getHxId();
		if(TextUtils.isEmpty(username)) return 0;
		Cursor cursor = sqlDB.rawQuery("select sum(count) from unreadcount where username != ? and username != 'admin'", new String[] { username });

		int count = 0;
		if (cursor.moveToFirst()) {
			count = cursor.getInt(0);
		}
		cursor.close();
		return count;
	}
	
	public synchronized int getPushMessageCount(){
		SQLiteDatabase sqlDB = DBHelper.getSQLiteDatabase();
		if(!tableIsExist(sqlDB, table)) return 0;
		Cursor cursor = sqlDB.rawQuery("select sum(count) from unreadcount where username = 'admin'", new String[]{});

		int count = 0;
		if (cursor.moveToFirst()) {
			count = cursor.getInt(0);
		}
		cursor.close();
		return count;
	}
	
	public synchronized void clearPushMessageCount(){
		updateUnreadCount("admin", 0);
	}

	public synchronized void updateUnreadCount(String username, int count) {
		try {
			SQLiteDatabase sqlDB = DBHelper.getSQLiteDatabase();
			ContentValues localContentValues = new ContentValues();
			localContentValues.put("username", username);
			localContentValues.put("count", count);
			sqlDB.replace("unreadcount", null, localContentValues);
		} catch (Exception localException) {
		}
	}
}
